import axios from 'axios'
import NProgress from 'nprogress/nprogress'
import 'nprogress/nprogress.css'
import { IS_NPROGRESS, TIMEOUT } from '../js/config'

let instance = axios.create()

instance.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(cancel => {
      window.__axiosPromiseArr.push({
        url: config.url,
        cancel
      })
    })
    if (config.method === 'post') {
      // config.headers['Authorization'] = 'Bearer ' + '8add4aee-fadc-4989-9a66-3306444ddbf4'
      config.params = {
        // openid: sessionStorage.getItem('openid'),
        // tenantId: localStorage.getItem('tenantId'),
        // // wechatId: localStorage.getItem('wechatId'),
        // wxAppid: sessionStorage.getItem('appid'),
        // appid: sessionStorage.getItem('appid')
        // browse: 'WeChat'
      }
    } else if (config.method === 'get') {
      // config.headers['Authorization'] = 'Bearer ' + '8add4aee-fadc-4989-9a66-3306444ddbf4'
      // // 有些get请求没有带params，此时都给他加上
      config.params = {
        // openid: sessionStorage.getItem('openid'),
        // tenantId: localStorage.getItem('tenantId'),
        // // wechatId: localStorage.getItem('wechatId'),
        // wxAppid: sessionStorage.getItem('appid'),
        // appid: sessionStorage.getItem('appid'),
        // browse: 'WeChat',
        ...config.params
      }
    }
    if (IS_NPROGRESS) {
      NProgress.start()
    }
    return config
  },
  err => {
    // console.log(err)
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  response => {
    if (IS_NPROGRESS) {
      NProgress.done()
    }
    return response.data
  },
  error => {
    if (IS_NPROGRESS) {
      NProgress.done()
    }
    return Promise.reject(error)
  }
)

instance.defaults.timeout = TIMEOUT

/* eslint-disable no-proto */
// 实例可以使用all，spread等方法
instance.__proto__ = axios
/* eslint-enable */

export default instance
